<!-- 添加企业 -->
<script setup lang="ts">
import {
  createEnterpriseAPI,
  getEnterpriseDetailAPI,
  getIndustryListAPI,
  updateEnterpriseAPI,
  uploadAPI,
} from "@/apis/enterprise";
import type { Industry } from "@/types/enterprise";
import { validMobile } from "@/utils/validate";
import {
  ElMessage,
  type UploadFile,
  type UploadFiles,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";

import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const addForm = ref({
  name: "", // 企业名称
  legalPerson: "", // 法人
  registeredAddress: "", // 注册地址
  industryCode: "", // 所在行业
  contact: "", // 企业联系人
  contactNumber: "", // 联系人电话
  businessLicenseUrl: "", // 营业执照url
  businessLicenseId: "", // 营业执照id
});

const route = useRoute();
// 接收页面传值
const id = computed(() => {
  return route.query.id as string;
});

onMounted(() => {
  // 有合同id 调用详情接口
  if (id.value) {
    getEnterpriseDetail();
  }
});
// 获取详情
const getEnterpriseDetail = async () => {
  const res = await getEnterpriseDetailAPI(id.value);
  const {
    businessLicenseId,
    businessLicenseUrl,
    contact,
    contactNumber,
    industryCode,
    legalPerson,
    name,
    registeredAddress,
    businessLicenseName,
  } = res.data;
  addForm.value = {
    businessLicenseId,
    businessLicenseUrl,
    contact,
    contactNumber,
    industryCode,
    legalPerson,
    name,
    registeredAddress,
  };
  fileList.value.push({
    name: businessLicenseName,
    url: businessLicenseUrl,
  });
};
const industryList = ref<Industry[]>([]); // 可选行业列表
const getIndustryList = async () => {
  const res = await getIndustryListAPI();
  industryList.value = res.data;
};
getIndustryList();

// 表单校验
const rules = ref({
  name: [
    {
      required: true,
      message: "请输入企业名称",
      trigger: "blur",
    },
  ],
  legalPerson: [{ required: true, message: "法人为必填", trigger: "blur" }],
  registeredAddress: [
    { required: true, message: "注册地址为必填", trigger: "blur" },
  ],
  industryCode: [
    { required: true, message: "所在行业为必填", trigger: "change" },
  ],
  contact: [{ required: true, message: "企业联系人为必填", trigger: "blur" }],
  contactNumber: [
    { required: true, message: "企业联系人电话为必填", trigger: "blur" },
    { validator: validMobile, trigger: "blur" },
  ],
  businessLicenseId: [
    { required: true, message: "请上传营业执照", trigger: "blur" },
  ],
});

// 营业执照上传
const fileList = ref<UploadUserFile[]>([]); // 营业执照列表
const uploadRequest = async (options: UploadRequestOptions): Promise<any> => {
  const file = options.file;

  // 处理formData类型参数
  const formData = new FormData();
  formData.append("file", file);
  formData.append("type", "businessLicense");
  const res = await uploadAPI(formData);

  // 赋值表单数据
  addForm.value.businessLicenseId = res.data.id;
  addForm.value.businessLicenseUrl = res.data.url;

  // el-upload 显示已上传文件列表
  // el-upload 组件要求列表对象必须有 name 和 url 属性才可以
  fileList.value.push({
    name: file.name,
    url: res.data.url,
  });
  // 单独校验表单，清除错误信息
  ruleForm.value.validateField("businessLicenseId");
};

// 移除
const onRemove = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  addForm.value.businessLicenseId = "";
  addForm.value.businessLicenseUrl = "";
  fileList.value = [];
};
// 上传文件前校验
const onExceed = (files: UploadRawFile[], fileList: UploadRawFile[]) => {
  ElMessage({
    message: "最多只能上传一个文件",
    type: "warning",
  });
};
// 上传前校验
const beforeUpload = (file: UploadRawFile) => {
  const allowImgType = ["image/jpeg", "image/png", "image/jpg"].includes(
    file.type
  );
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!allowImgType) {
    ElMessage.error("上传营业执照图片只能是 PNG/JPG/JPEG 格式!");
  }
  if (!isLt5M) {
    ElMessage.error("上传营业执照图片大小不能超过 5MB!");
  }
  return allowImgType && isLt5M;
};

const ruleForm = ref();
const router = useRouter();
// 点击提交时候校验
const confirmSubmit = () => {
  ruleForm.value.validate(async (valid: boolean) => {
    if (valid) {
      // 如果是编辑跳转过来调用编辑更新接口
      if (id.value) {
        // 编辑
        await updateEnterpriseAPI({
          ...addForm.value,
          id: id.value,
        });
      } else {
        // 调用接口
        await createEnterpriseAPI(addForm.value);
      }
      // 返回列表页
      router.back();
    }
  });
};
// 重置
const resetData = () => {
  addForm.value.name = "";
  addForm.value.legalPerson = "";
  addForm.value.contact = "";
  addForm.value.contactNumber = "";
  addForm.value.registeredAddress = "";
  addForm.value.industryCode = "";
  addForm.value.businessLicenseUrl = "";
  addForm.value.businessLicenseId = "";
};
</script>

<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header
        :content="id ? '编辑企业' : '添加企业'"
        @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form
            ref="ruleForm"
            label-width="100px"
            :rules="rules"
            :model="addForm">
            <el-form-item label="企业名称">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业">
              <el-select v-model="addForm.industryCode">
                <!-- 行业下来列表 -->
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName" />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照">
              <el-upload
                action="#"
                :file-list="fileList"
                :http-request="uploadRequest"
                :on-remove="onRemove"
                :before-upload="beforeUpload"
                :on-exceed="onExceed"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  支持扩展名：.png .jpg .jpeg, 文件大小不得超过5M
                </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetData">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
